package com.mofang.powerdekorhelper.activity.customer;

import android.app.Dialog;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.TextView;

import com.mofang.powerdekorhelper.R;
import com.mofang.powerdekorhelper.activity.order.OrderDetailActivity;
import com.mofang.powerdekorhelper.activity.order.OrderEditActivity;
import com.mofang.powerdekorhelper.adapter.ActivityRecordAdapter;
import com.mofang.powerdekorhelper.adapter.CommentRecordAdapter;
import com.mofang.powerdekorhelper.adapter.CommunicationRecordAdapter;
import com.mofang.powerdekorhelper.adapter.OrderAdapter;
import com.mofang.powerdekorhelper.base.MvpActivity;
import com.mofang.powerdekorhelper.base.recycleview.BaseRecycleViewList;
import com.mofang.powerdekorhelper.model.CreateOrder;
import com.mofang.powerdekorhelper.model.CustomerActivity;
import com.mofang.powerdekorhelper.model.CustomerDetail;
import com.mofang.powerdekorhelper.model.Order;
import com.mofang.powerdekorhelper.model.OrderDetial;
import com.mofang.powerdekorhelper.model.ResultMessage;
import com.mofang.powerdekorhelper.persenter.CustomerDetialPersenter;
import com.mofang.powerdekorhelper.utils.DialogUtils;
import com.mofang.powerdekorhelper.utils.LoadPrograss;
import com.mofang.powerdekorhelper.utils.ParamsUtils;
import com.mofang.powerdekorhelper.utils.SharePerforenceUtils;
import com.mofang.powerdekorhelper.utils.T;
import com.mofang.powerdekorhelper.view.CustomerDetialView;
import com.mofang.powerdekorhelper.witget.TitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by luofei on 2017/8/24 0024.
 */

public class CustomerDetialActivity extends MvpActivity<CustomerDetialView, CustomerDetialPersenter> implements
        CustomerDetialView, OrderAdapter.IOrderClick {

    public final static int mRequestCode = 100;
    public final static int mChooseActivityCode = 101;

    @BindView(R.id.customer_detial_titlebar)
    TitleBar mTitleBar;

    @BindView(R.id.customer_detail_name)
    TextView customerNameTv;

    @BindView(R.id.customer_detail_phone)
    TextView customerPhoneTv;

    @BindView(R.id.customer_detail_address)
    TextView customerAddressTv;

    @BindView(R.id.customer_state_tv)
    TextView stateTv;

    @BindView(R.id.customer_way_tv)
    TextView wayTv;

    @BindView(R.id.customer_detail_activity_list)
    BaseRecycleViewList activityRecycle;

    @BindView(R.id.customer_detail_order_list)
    BaseRecycleViewList orderRecycle;

    @BindView(R.id.customer_detail_chat_list)
    BaseRecycleViewList CommunicationRecycle;

    @BindView(R.id.customer_detail_comment_list)
    BaseRecycleViewList commentRecycle;

    Integer customerId;
    Integer sellerId;
    Integer shopId;
    private Dialog generateDialog;
    String orderCode = "";
    String customerPhone;
    Integer activityId;
    Dialog commitDialog = null;
    String customerName;

    private LoadPrograss loadPrograss;

    private int lastState;

    @Override
    public void initView() {

        inflateLayout(R.layout.activity_customer_detial_layout);
        initTitleBarWithback(mTitleBar, R.string.customer_detail);

        activityRecycle.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        orderRecycle.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        CommunicationRecycle.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        commentRecycle.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        loadPrograss = new LoadPrograss(this);
    }

    @Override
    public void initData() {
        customerId = getIntent().getIntExtra("CustomerId", -1);
        sellerId = SharePerforenceUtils.getInstance(this).getUserID();
        shopId = SharePerforenceUtils.getInstance(this).getShopId();
        presenter.getCustomerDetail(customerId, sellerId, shopId);
    }

    @OnClick({R.id.customer_detail_add_record, R.id.customer_detail_create_order})
    void onclick(View view) {
        switch (view.getId()) {
            case R.id.customer_detail_add_record:

                startActivityForResult(new Intent(this, AddCommunicationRecordActivity.class)
                        .putExtra("CustomerId", customerId), mRequestCode);
                break;

            case R.id.customer_detail_create_order:
                presenter.getCustomerActivity(customerId, shopId);
                break;
        }
    }

    @Override
    public void setCustomerActivity(CustomerActivity customerActivity) {

        if (customerActivity.getResult().size() > 1) {

            startActivityForResult(new Intent(this, ChooseActivityListAct.class)
                    .putExtra("CustomerActivity", customerActivity), mChooseActivityCode);
        } else {
            activityId = customerActivity.getResult().get(0).getActivity_id();
            customerPhone = customerPhoneTv.getText().toString();
            customerName = customerNameTv.getText().toString();
            presenter.getCreateOrder(customerPhone, "");
            DialogUtils.getInstance().createLoadingDialog(CustomerDetialActivity.this, "正在生成订单，请稍候");
        }
    }

    @Override
    public void setCreateOrder(CreateOrder createOrder) {

        hideProgress();

        if (createOrder.getCode().equals("2")) {
            toast(createOrder.getMessage());
        } else {
            if (createOrder.getResult() != null) {
                orderCode = createOrder.getResult().getOrderBillNo();
                if (generateDialog != null && generateDialog.isShowing()) {
                    generateDialog.dismiss();
                }
            } else {
                createOrder = null;
                toast("订单号无法匹配请重新输入");
            }
            generateDialog = new DialogUtils().GenerateOrderDialog(this, createOrder, new DialogUtils.IGenerateOrder() {
                @Override
                public void getOrderCode(String orderCode, String name, String phone) {
                    // 确定
                    if (!orderCode.equals("")) {

                        generateDialog.dismiss();
                        presenter.getCheckOrder(ParamsUtils.getcheckOrderParams(orderCode, activityId, shopId, customerId));
                    } else {
                        toast("订单号为空无法生成订单");
                    }
                }

                @Override
                public void onRefresh(String orderCode) {
                    // 刷新
                    generateDialog.dismiss();
                    presenter.getCreateOrder("", orderCode);
                    DialogUtils.getInstance().createLoadingDialog(CustomerDetialActivity.this, "正在生成订单，请稍候");
                }

                @Override
                public void cancleDialog() {
                    // 取消
                    generateDialog.dismiss();
                }
            });
            generateDialog.show();
        }


        hideProgress();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mRequestCode) {

            presenter.getCustomerDetail(customerId, sellerId, shopId);
        }

        if (requestCode == mChooseActivityCode) {

            activityId = data.getIntExtra("ActivityId", -1);

            String customerPhone = customerPhoneTv.getText().toString();

            presenter.getCreateOrder(customerPhone, "");

            DialogUtils.getInstance().createLoadingDialog(CustomerDetialActivity.this, "正在生成订单，请稍候");
        }
    }

    @Override
    public void setCheckOrder(OrderDetial orderDetial) {

        if (orderDetial.getCode().equals("2")) {
            toast(orderDetial.getMessage());
        } else {
            if (orderDetial.getResult() != null) {
                startActivityForResult(new Intent(CustomerDetialActivity.this, OrderEditActivity.class)
                        .putExtra("EnterFlag", 1)
                        .putExtra("enterFlag2", 2)
                        .putExtra("IsEditState", true)
                        .putExtra("OrderCode", orderDetial.getResult().getOrderCode())
                        .putExtra("ActivityId", activityId)
                        .putExtra("CustomerId", customerId)
                        .putExtra("CustomerName", customerName)
                        .putExtra("CustomerPhone", customerPhone), 111);
            } else {
                toast("订单号无法匹配请重新输入");
            }
        }

        hideProgress();
    }

    @Override
    public void setCustomerDetial(CustomerDetail customerDetial) {

        if (customerDetial.getResult().getCustomerInfo() != null) {
            customerNameTv.setText(customerDetial.getResult().getCustomerInfo().getCustomerName());

            customerPhone = customerDetial.getResult().getCustomerInfo().getCustomerPhone();
            customerPhoneTv.setText(customerPhone);
            customerAddressTv.setText(customerDetial.getResult().getCustomerInfo().getConsignee_address());

            int property = customerDetial.getResult().getCustomerInfo().getProperty();
            if (property == 1) {
                wayTv.setText("公司分配");
            } else {
                wayTv.setText("邀请注册");
            }

            Integer state = customerDetial.getResult().getCustomerInfo().getCommunicationStatus();
            if (state != null) {
                String stateStr = "";
                switch (state) {
                    case 1:
                        stateStr = "已联系";
                        break;
                    case 2:
                        stateStr = "已进店";
                        break;
                    case 3:
                        stateStr = "已购卡";
                        break;
                    case 4:
                        stateStr = "已订单";
                        break;
                    case 5:
                        stateStr = "已活动";
                        break;
                    case 6:
                        stateStr = "已物流";
                        break;
                    case 7:
                        stateStr = "已安装";
                        break;
                    case 8:
                        stateStr = "售后中";
                        break;
                    case 9:
                        stateStr = "已关闭";
                        break;
                }
                stateTv.setText(stateStr);
            } else {
                stateTv.setText("无");
            }
        }

        if (customerDetial.getResult().getCustomerActivity() != null) {

            ActivityRecordAdapter adapter = new ActivityRecordAdapter(customerDetial.getResult().getCustomerActivity(), this, R.layout.activity_record_list_item_layout);

            adapter.setiDetailCall(new ActivityRecordAdapter.IDetailCall() {
                @Override
                public void Idetail(Integer activityId) {

                    startActivity(new Intent(CustomerDetialActivity.this, CustomerActivityDetailAct.class)
                            .putExtra("ActivityId", activityId)
                            .putExtra("CustomerId", customerId));
                }
            });

            activityRecycle.setAdapter(adapter);
        }

        List<CustomerDetail.CustomerOrder> orders = customerDetial.getResult().getCustomerOrder();

        List<Order.Data> datas = new ArrayList<>();

        if (orders != null) {

            for (CustomerDetail.CustomerOrder order : orders) {

                Order.Data data = new Order().new Data();
                data.setOrderCode(order.getOrder_code());
                data.setOrderState(order.getOrderState());
                data.setCustomerName(order.getCustomerName());
                data.setCustomerPhone(order.getCustomerPhone());
                data.setProductModel(order.getProduct_model());
                data.setOrderPrice(order.getOrder_price());
                data.setCreateTime(order.getCreateTime());
                data.setOrderId(order.getOrderId());
                data.setActivityId(order.getActivityId());
                datas.add(data);
            }

            OrderAdapter adapter = new OrderAdapter(datas, this, R.layout.order_list_item_layout);
            adapter.setOrderClick(this);
            orderRecycle.setAdapter(adapter);
        }

        List<CustomerDetail.CustomerCommunication> communications = customerDetial.getResult().getCustomerCommunication();
        if (communications != null) {
            CommunicationRecordAdapter adapter = new CommunicationRecordAdapter(communications, this, R.layout.communication_record_list_item);
            CommunicationRecycle.setAdapter(adapter);
            if (communications.size() > 0) {
                if (communications.get(0) != null) {
                    lastState = communications.get(0).getState();
                }
            }
        }

        List<CustomerDetail.CustomerEvaluate> Comments = customerDetial.getResult().getCustomerEvaluate();
        if (Comments != null) {
            CommentRecordAdapter adapter = new CommentRecordAdapter(Comments, this, R.layout.comment_record_list_item_layout);
            commentRecycle.setAdapter(adapter);
        }
    }

    @Override
    public void orderRefresh(int orderId, String orderCode, int activityId, int customerId) {
    }

    // 订单详情
    @Override
    public void orderDetail(int orderId) {
        startActivity(new Intent(CustomerDetialActivity.this, OrderDetailActivity.class).putExtra("OrderId", orderId));
    }

    @Override
    public void orderClose(final int orderId, int orderState) {

        commitDialog = DialogUtils.getInstance().CommitInfoDialog(this, new DialogUtils.IgetCommitInfo() {
            @Override
            public void getCommitInfo(String commitInfo) {

                if (!commitInfo.trim().equals("")) {

                    presenter.getCloseOrder(ParamsUtils.getCloseOrder(orderId, commitInfo));

                } else {
                    toast("请输入关闭理由");
                }
            }

            @Override
            public void cancleDialog() {
                commitDialog.dismiss();
            }
        });
        commitDialog.show();
    }

    @Override
    public void setCloseOrder(ResultMessage resultMessage) {
        hideProgress();
        commitDialog.dismiss();
        toast("关闭订单成功");
    }

    @Override
    public void showProgress() {
        loadPrograss.show();
    }

    @Override
    public void hideProgress() {
        loadPrograss.hide();
        DialogUtils.getInstance().hideLoadingDialog();
    }

    @Override
    public void toast(CharSequence s) {

        T.showShort(this, s);
    }

    @Override
    public void toast(int id) {

    }

    @Override
    public void showNullLayout() {
        loadPrograss.hide();
        hideProgress();
        toast("订单号无法匹配请重新输入");
    }

    @Override
    public void hideNullLayout() {
        loadPrograss.hide();
    }

    @Override
    public void showErrorLayout(View.OnClickListener listener) {
        loadPrograss.hide();
    }

    @Override
    public void hideErrorLayout() {
        loadPrograss.hide();
    }

    @Override
    public void onError(String errorInfo) {
        loadPrograss.hide();
        DialogUtils.getInstance().hideLoadingDialog();
        toast(errorInfo);
    }

    @Override
    public CustomerDetialPersenter initPresenter() {
        return new CustomerDetialPersenter();
    }
}
